package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.ResponseHandlerInterface;
import com.loopj.ohos.http.ext.LocalHiLog;
import com.loopj.ohos.http.sample.services.ExampleIntentService;
import com.loopj.ohos.http.sample.util.IntentUtil;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.event.commonevent.*;
import ohos.rpc.RemoteException;

import java.nio.charset.Charset;

/**
 * IntentServiceSample
 */
public class IntentServiceSample extends SampleParentAbility {
    /**
     * String
     */
    public static final String LOG_TAG = "IntentServiceSample";
    /**
     * String
     */
    public static final String ACTION_START = "SYNC_START";
    /**
     * String
     */
    public static final String ACTION_RETRY = "SYNC_RETRY";
    /**
     * String
     */
    public static final String ACTION_CANCEL = "SYNC_CANCEL";
    /**
     * String
     */
    public static final String ACTION_SUCCESS = "SYNC_SUCCESS";
    /**
     * String
     */
    public static final String ACTION_FAILURE = "SYNC_FAILURE";
    /**
     * String
     */
    public static final String ACTION_FINISH = "SYNC_FINISH";
    /**
     * String
     */
    public static final String[] ALLOWED_ACTIONS = {ACTION_START,
            ACTION_RETRY, ACTION_CANCEL, ACTION_SUCCESS, ACTION_FAILURE, ACTION_FINISH};

    private class HCommonEventSubscriber extends CommonEventSubscriber {

        public HCommonEventSubscriber(CommonEventSubscribeInfo subscribeInfo) {
            super(subscribeInfo);
        }

        @Override
        public void onReceiveEvent(CommonEventData commonEventData) {
            LocalHiLog.info(LOG_TAG, "commonEventData is " + commonEventData.toString());
            final Intent intent = commonEventData.getIntent();
            String action = intent.getAction();
            LocalHiLog.info(LOG_TAG, "action is " + action);

            // switch() doesn't support strings in older JDK.
            if (ACTION_START.equals(action)) {
                clearOutputs();
                addView(getColoredView(LIGHTBLUE, "Request started"));
            } else if (ACTION_FINISH.equals(action)) {
                addView(getColoredView(LIGHTBLUE, "Request finished"));
            } else if (ACTION_CANCEL.equals(action)) {
                addView(getColoredView(LIGHTBLUE, "Request cancelled"));
            } else if (ACTION_RETRY.equals(action)) {
                addView(getColoredView(LIGHTBLUE, "Request retried"));
            } else if (ACTION_FAILURE.equals(action) || ACTION_SUCCESS.equals(action)) {
                debugThrowable(LOG_TAG, (Throwable) intent.getSerializableParam(ExampleIntentService.INTENT_THROWABLE));
                if (ACTION_SUCCESS.equals(action)) {
                    debugStatusCode(LOG_TAG, intent.getIntParam(ExampleIntentService.INTENT_STATUS_CODE, 0));
                    debugHeaders(LOG_TAG, IntentUtil.deserializeHeaders(intent.getStringArrayParam(ExampleIntentService.INTENT_HEADERS)));
                    byte[] returnedBytes = intent.getByteArrayParam(ExampleIntentService.INTENT_DATA);
                    if (returnedBytes != null) {
                        debugResponse(LOG_TAG, new String(returnedBytes, Charset.defaultCharset()));
                    }
                }
            }
        }
    }

    private HCommonEventSubscriber broadcastReceiver;

    @Override
    protected void onActive() {
        LocalHiLog.info(LOG_TAG, "onActive.");
        super.onActive();

        MatchingSkills matchingSkills = new MatchingSkills();

        for (String action : ALLOWED_ACTIONS) {
            matchingSkills.addEvent(action);
        }

        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        broadcastReceiver = new HCommonEventSubscriber(subscribeInfo);

        try {
            CommonEventManager.subscribeCommonEvent(broadcastReceiver);
            LocalHiLog.info(LOG_TAG, "subscribeCommonEvent success.");
        } catch (RemoteException e) {
            LocalHiLog.error(LOG_TAG, "subscribeCommonEvent occur exception.");
        }
    }

    @Override
    protected void onInactive() {
        LocalHiLog.info(LOG_TAG, "onInactive.");
        super.onInactive();
        try {
            CommonEventManager.unsubscribeCommonEvent(broadcastReceiver);
            LocalHiLog.info(LOG_TAG, "unsubscribeCommonEvent success.");
        } catch (RemoteException e) {
            LocalHiLog.error(LOG_TAG, "unsubscribeCommonEvent occur exception.");
        }
    }

    @Override
    public ResponseHandlerInterface getResponseHandler() {
        // no response handler on activity
        return null;
    }

    @Override
    public String getDefaultURL() {
        return "https://httpbin.org/get";
    }

    @Override
    public boolean isRequestHeadersAllowed() {
        return false;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_intent_service_sample;
    }

    @Override
    public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) {
        Intent serviceCall = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.loopj.ohos.http.sample")
                .withAbilityName("com.loopj.ohos.http.sample.services.ExampleIntentService")
                .build();
        serviceCall.setOperation(operation);

        serviceCall.setParam(ExampleIntentService.INTENT_URL, URL);
        startAbility(serviceCall);

        return null;
    }
}
